package com.example.apigateway;

import com.example.apiclientsdk.utils.SignUtils;
import com.example.apicommon.model.entity.InterfaceInfo;
import com.example.apicommon.model.entity.User;
import com.example.apicommon.model.entity.UserInterfaceInfo;
import com.example.apicommon.service.InnerInterfaceInfoService;
import com.example.apicommon.service.InnerUserInterfaceInfoService;
import com.example.apicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    private static final String INTERFACE_HOST = "http://192.168.200.128:8234";

//    public static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1", "127.0.0.2");

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.请求日志
        ServerHttpRequest request = exchange.getRequest();

        String path = INTERFACE_HOST + request.getPath().value();
        String method = request.getMethod().toString();

        log.info("请求唯一标识ID,{}", request.getId());
        log.info("请求路径,{}", request.getPath());
        log.info("请求参数,{}", request.getQueryParams());
        log.info("请求请求方法,{}", request.getMethod());
        log.info("请求来源地址,{}", request.getLocalAddress().getHostString());
        log.info("请求来源地址,{}", request.getRemoteAddress());
//        //2.ip黑白名单
//        String hostString = request.getLocalAddress().getHostString();
        ServerHttpResponse response = exchange.getResponse();
//        if (!IP_WHITE_LIST.contains(hostString)) {
//            response.setStatusCode(HttpStatus.FORBIDDEN);
//            return response.setComplete();
//        }
        //3.鉴权

        String accessKey = request.getHeaders().getFirst("accessKey");
        String nonce = request.getHeaders().getFirst("nonce");
        String timestamp = request.getHeaders().getFirst("timestamp");
        String sign = request.getHeaders().getFirst("sign");
        String body = request.getHeaders().getFirst("body");
        //远程调用接口去数据库中查是否已分配给用户
        User invokeUser = null;
        try {
            invokeUser = innerUserService.getInvokeUser(accessKey);
        } catch (Exception e) {
            log.error("getInvokeUser error", e);
        }
        if (invokeUser == null) {
            return handleNoAuth(response);
        }
//        if (!accessKey.equals("wsc")) {
//            return handleNoAuth(response);
//        }
        if (Long.parseLong(nonce) > 10000) {
            return handleNoAuth(response);
        }
        Long currentTime = System.currentTimeMillis() / 1000;
        final Long ONE_MINUTES = 60 * 1L;
        if ((currentTime - Long.parseLong(timestamp)) >= ONE_MINUTES) {
            return handleNoAuth(response);
        }

        //todo 实际情况中是从数据库中查出 secretKey
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.genSign(body, secretKey);
        if (sign == null || !sign.equals(serverSign)) {
            return handleNoAuth(response);
        }
        // 4. 请求的模拟接口是否存在，以及请求方法是否匹配
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
        } catch (Exception e) {
            log.error("getInterfaceInfo error", e);
        }
        if (interfaceInfo == null) {
            return handleNoAuth(response);
        }

        //5.调用外部接口查看接口是否还有调用次数
        UserInterfaceInfo userInterfaceInfo = null;
        try {
            userInterfaceInfo = innerUserInterfaceInfoService.getLeftNum(interfaceInfo.getId(), invokeUser.getId());
        } catch (Exception e) {
            log.error("getUserInterfaceInfo error", e);
        }
        if (userInterfaceInfo == null || userInterfaceInfo.getLeftNum() <= 0) {
            return handleNoAuth(response);
        }


        return getVoidMono(exchange, chain, interfaceInfo.getId(), invokeUser.getId());
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange, GatewayFilterChain chain, long interfaceInfoId, long userId) {


        try {
            //7/调用失败,返回规范的错误代码
            ServerHttpResponse response = exchange.getResponse();

            DataBufferFactory bufferFactory = response.bufferFactory();

            HttpStatus statusCode = response.getStatusCode();
            if (statusCode.equals(HttpStatus.OK)) {
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                // 调用成功，接口调用次数 + 1 invokeCount
                                try {
                                    innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                } catch (Exception e) {
                                    log.error("invokeCount error", e);
                                }

                                // 拼接返回数据
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 6.构建响应日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(response.getStatusCode());
                                String data = new String(content, StandardCharsets.UTF_8); //data
                                sb2.append(data);
                                //输出日志
                                log.info("响应状态码为{}", sb2);

                                return bufferFactory.wrap(content);
                            }));
                        }
                        return super.writeWith(body); // if body is not a flux. never got there.
                    }
                };

                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }


            return chain.filter(exchange);
        } catch (Exception e) {
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    private Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}